﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web.Services.Protocols;

namespace JiraGenCommon.JiraServices
{
    class JiraSoapExtensions: SoapExtension
    {
        private Stream m_inwardStream;
        private Stream m_outwardStream;

        public override void ProcessMessage(SoapMessage message)
        {
            string _soapMsg;
            StreamReader _readStr;
            StreamWriter _writeStr;

            switch (message.Stage)
            {
                case SoapMessageStage.BeforeSerialize:
                    break;
                case SoapMessageStage.AfterDeserialize:
                    break;
                case SoapMessageStage.BeforeDeserialize:
                    _readStr = new StreamReader(m_outwardStream);
                    _writeStr = new StreamWriter(m_inwardStream);
                    _soapMsg = _readStr.ReadToEnd();

                    switch (message.MethodInfo.Name)
                    {
                        case "getWorklogs":
                        case "addWorklogWithNewRemainingEstimate":
                        case "addWorklogAndAutoAdjustRemainingEstimate":
                        case "addWorklogAndRetainRemainingEstimate":
                            _soapMsg = _soapMsg.Replace("RemoteWorklogImpl", "RemoteWorklog").Replace("service", "beans");
                            break;

                    }
                    _writeStr.Write(_soapMsg);
                    _writeStr.Flush();
                    m_inwardStream.Position = 0;
                    break;
                case SoapMessageStage.AfterSerialize:
                    m_inwardStream.Position = 0;
                    _readStr = new StreamReader(m_inwardStream);
                    _writeStr = new StreamWriter(m_outwardStream);
                    _soapMsg = _readStr.ReadToEnd();

                    _writeStr.Write(_soapMsg);
                    _writeStr.Flush();
                    break;
            }
        }

        public override Stream ChainStream(Stream stream)
        {
            m_outwardStream = stream;
            m_inwardStream = new MemoryStream();
            return m_inwardStream;
        }

        public override object GetInitializer(Type type)
        {
            return GetType();
        }

        public override object GetInitializer(LogicalMethodInfo info, SoapExtensionAttribute attribute)
        {
            return null;
        }

        public override void Initialize(object initializer)
        {
        }
    }
}
